package com.net.common.web;

import java.math.BigDecimal;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.template.SimpleNumber;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;

/**
 * @author  on 2017/7/25.
 * 百分比的数据:百分比数据是 *10000的,保留两位小数
 */
public class PercentTemplateMethodModelEx implements TemplateMethodModelEx {
    private static final Logger LOGGER = LoggerFactory.getLogger(PercentTemplateMethodModelEx.class);

    @Override
    public Object exec(List arguments) throws TemplateModelException {
        if (arguments == null || arguments.size() != 1) {
            LOGGER.warn("Wrong percent arguments");
            return "";
        }
        SimpleNumber value = (SimpleNumber) arguments.get(0);

        if (value == null || value.getAsNumber() == null) {
            LOGGER.warn("Wrong percent arguments empty");
            return "";
        }

        return new BigDecimal(value.getAsNumber().longValue()).multiply(new BigDecimal("0.01")).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
    }
}
